typescript의 non-null assertion은 컴파일시에 사라진다
ChatGPT 4o Answer
⚠️ Using TypeScript's Non-Null Assertion Operator (!
) Safely
🧠 What Is the Non-Null Assertion Operator?
In TypeScript, the !
operator can be placed after an expression to tell the compiler:
“I know this value is not
null
orundefined
— trust me.”
Example:
const element = document.getElementById('header')!;
This bypasses the compiler’s type checks, assuming element
is always present.
🚨 Why It Can Be Dangerous
-
Silent runtime failures: If the value actually is
null
orundefined
, the program will throw a runtime error. -
Hidden bugs: This bypasses TypeScript's static safety guarantees, leading to bugs that are hard to trace.
-
Overconfidence in external data: It often assumes upstream guarantees (e.g., query results, user input) that might not hold in real-world conditions.
✅ Best Practice: Validate First, Assert Last
Instead of:
const data = fetchDataById(id)!;
Use:
if (!id) {
throw new Error('Missing id');
}
const data = await fetchDataById(id);
if (!data) {
throw new Error('Data not found');
}
Or return structured results:
if (!id) return { success: false, reason: 'INVALID_ID' };
const data = await repo.find(id);
if (!data) return { success: false, reason: 'NOT_FOUND' };
🧾 Summary
❌ Avoid | ✅ Prefer |
---|---|
Blindly using ! |
Explicit null/undefined checks |
Trusting unsafe input | Defensive programming |
Relying on assumptions | Handling edge cases gracefully |
Rule of thumb: If you're reaching for !
, ask yourself: "What if I'm wrong?"
Would you like a Markdown version of this for internal documentation or onboarding?